#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <iostream>

#include "InetAddr.hpp"
#include "Log.hpp"
#include "Common.hpp"
// 创建 类域名
namespace SocketModule
{
    using namespace LogModule;
    const static int gbacklog = 16;

    // 模版方法模式
    // 基类socket, 大部分方法，都是纯虚方法
    class Socket
    {
        public:
        
        //各种接口: bind, listen, socket, 
        virtual ~Socket() {}
        virtual void SocketOrDie() = 0;
        virtual void BindOrDie(uint16_t port) = 0;
        virtual void ListenOrDie(int backlog = gbacklog) = 0;
        virtual std::shared_ptr<Socket> AcceptOrDie(InetAddr* client) = 0;
        virtual int Send(std::string &message) = 0;
        virtual int Recv(std::string *out) = 0;
        virtual void Close() = 0;
        virtual int Connect(std::string ip, uint16_t port) = 0;

        public:
        //直接 把过程接口化， 可读性更高  建立tcpsocket方法
        void BuildTcpSocketMethod(uint16_t port, int backlog = gbacklog)
        {
            SocketOrDie();
            BindOrDie(port);
            ListenOrDie(backlog);
        }

        void BuildClientTcpSocketMethod()
        {
            SocketOrDie();
        }
    };

    const int defaultfd = -1;
    
    //TcpSocket 基础 socket类，如此更方便
    class TcpSocket : public Socket
    {
        public:
        //根据socket 的虚函数，自己完成对应的操作接口
        TcpSocket():_sockfd(defaultfd)
        {}
        TcpSocket(int fd):_sockfd(fd)
        {}
        ~TcpSocket() {}

        //sockfd - tcp - INET STREAM
        void SocketOrDie() override
        {
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if(_sockfd < 0)
            {
                LOG(LogLevel::FATAL) << "socker error";
                exit(SOCKET_ERR);
            }
            LOG(LogLevel::INFO) << "socker success";

        }

        void BindOrDie(uint16_t port) override
        {
            InetAddr client(port);
            int n = bind(_sockfd, client.NetAddrPtr(), client.NetAddrLen());
            if(n < 0)
            {
                LOG(LogLevel::FATAL) << "bind error";
                exit(BIND_ERR);
            }
            LOG(LogLevel::INFO) << "bind success";
        }

        void ListenOrDie(const int backlog) override
        {
            int n = listen(_sockfd, backlog);
            if(n < 0)
            {
                LOG(LogLevel::FATAL) << "listen error";
                exit(LISTEN_ERR);
            }
            LOG(LogLevel::INFO) << "listen success";
        }

        std::shared_ptr<Socket> AcceptOrDie(InetAddr* client) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            //注意这种 要传地址的 
            int fd = ::accept(_sockfd, CONV(peer), &len);
            if(fd < 0)
            {
                LOG(LogLevel::WARNING) << "accept fail ......";
                return nullptr; 
            }
            LOG(LogLevel::INFO) << "accept success";
            
            client->SetAddr(peer);
            return std::make_shared<TcpSocket>(fd);
        }

        void Close() override//??
        {
            if(_sockfd >= 0)
                ::close(_sockfd);
        }

        int Recv(std::string *out) override
        {
            // 流式读取，不关心读到的是什
            char buffer[1024];
            ssize_t n = ::recv(_sockfd, buffer, sizeof(buffer) - 1, 0);
            if(n > 0)
            {
                buffer[n] = 0;
                *out += buffer; //故意 +=
                //用于 保证能读取一个完整的报文
            }
            return n;
        }

        int Send(std::string &message) override
        {
            return send(_sockfd, message.c_str(), message.size(), 0);
        }


        int Connect(std::string ip, uint16_t port) override
        {
            InetAddr server(ip, port);
            int n = connect(_sockfd, server.NetAddrPtr(), server.NetAddrLen());
            if(n < 0)
            {
                LOG(LogLevel::WARNING) << "connect error .....";
                return n;
            }
            return n;
        }

        private:
        // _sockfd , listensockfd, sockfd;
        //一个 描述符，通过一个接口 可以代表 各种描述符
        // 如此的好处就是 listenfd 也能用 tcpserver的各种接口
        int _sockfd;
    };

}